<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 警告区域 -->
            <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable='false' show-icon>
            </el-alert>
            <!-- 商品分类区域 -->
            <el-row class="shop_list">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 级联选择器区域 -->
                    <el-cascader v-model="selectKeys" :options="cateList" :props="cateProps" @change="handleChange">
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- tab 页签区域 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 添加动态参数区域 -->
                <el-tab-pane label="动态参数" name="many">
                    <el-button size='mini' type='primary' :disabled='isBtnDisable' @click='addDialogVisible=true'>动态参数
                    </el-button>
                    <!-- 动态参数表格区域 -->
                    <el-table :data='manyTableData' border stripe>
                        <!-- 下拉列 -->
                        <el-table-column type='expand'>
                            <template slot-scope='scope'>
                                <el-tag :key='index' v-for='(item,index) in scope.row.attr_vals' closable
                                    @close='handleClose(index,scope.row)'>{{item}}
                                </el-tag>
                                <!-- 文本框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- 按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type='index'></el-table-column>
                        <el-table-column prop='attr_name' label='参数名称'></el-table-column>
                        <el-table-column label='操作'>
                            <template slot-scope='scope'>
                                <el-button size='mini' type="primary" icon="el-icon-edit"
                                    @click='editDialogVisibleShow(scope.row.attr_id)'>修改</el-button>
                                <el-button size='mini' type="danger" icon="el-icon-delete"
                                    @click='removeParams(scope.row.attr_id)'>删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 添加静态属性区域 -->
                <el-tab-pane label="静态属性" name="only">
                    <el-button size='mini' type='primary' :disabled='isBtnDisable' @click='addDialogVisible=true'>静态属性
                    </el-button>
                    <!-- 静态属性表格区域 -->
                    <el-table :data='onlyTableData' border stripe>
                        <!-- 下拉列 -->
                        <el-table-column type='expand'>
                            <template slot-scope='scope'>
                                <!-- 循环渲染标签 -->
                                <el-tag :key='index' v-for='(item,index) in scope.row.attr_vals' closable
                                    @close='handleClose(index,scope.row)'>{{item}}
                                </el-tag>
                                <!-- 文本框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- 按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type='index'></el-table-column>
                        <el-table-column prop='attr_name' label='属性名称'></el-table-column>
                        <el-table-column label='操作'>
                            <template slot-scope='scope'>
                                <el-button size='mini' type="primary" icon="el-icon-edit"
                                    @click='editDialogVisibleShow(scope.row.attr_id)'>修改</el-button>
                                <el-button size='mini' type="danger" icon="el-icon-delete"
                                    @click='removeParams(scope.row.attr_id)'>删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
            <!-- 添加参数弹框 -->
            <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%"
                @close='addDialogVisibleClose'>
                <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
                    <el-form-item :label="titleText" prop="attr_name">
                        <el-input v-model="addForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addParams">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 编辑参数弹框 -->
            <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%"
                @close='editDialogVisibleClose'>
                <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
                    <el-form-item :label="titleText" prop="attr_name">
                        <el-input v-model="editForm.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="editParams">确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                // 商品分类列表
                cateList: [],
                // 级联选择器的配置对象
                cateProps: {
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children',
                    expandTrigger: 'hover'
                },
                // 用户在级联下拉菜单中选中的分类id
                selectKeys: [],
                // 选中的页签名称
                activeName: 'many',
                //用来保存动态参数数据
                manyTableData: [],
                //用来保存静态属性数据
                onlyTableData: [],
                // 控制添加参数弹框是否显示 
                addDialogVisible: false,
                // 添加参数表单
                addForm: {
                    attr_name: ''
                },
                addFormRules: {
                    attr_name: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ]
                },
                // 控制编辑参数弹框是否显示
                editDialogVisible: false,
                editForm: {
                    attr_name: '',
                    attr_id: ''
                },
                editFormRules: {
                    attr_name: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ]
                },
            }
        },
        created() {
            this.getCateList()
        },
        methods: {
            // 获取商品分类数据列表
            async getCateList() {
                const { data: res } = await this.$axios.get('categories');
                if (res.meta.status !== 200) return this.$message.error('获取数据失败');
                this.cateList = res.data;
                // console.log(res.data);
            },
            // 级联选择器发生变化 会触发这个函数
            async handleChange() {
                if (this.selectKeys.length !== 3) {
                    this.selectKeys = [];
                    // 清空表格数据
                    this.manyTableData = [];
                    this.onlyTableData = [];
                    return
                }
                // console.log(this.selectKeys);

                // 获取参数列表
                const { data: res } = await this.$axios.get(`categories/${ this.cateId }/attributes`, {
                    params: { sel: this.activeName }
                });
                if (res.meta.status !== 200) return this.$message.error('获取数据失败');
                // console.log(res.data);

                // 将获取到的数据中的attr_vals字符串转换为数组
                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
                    // 控制文本框和按钮切换显示与隐藏
                    item.inputVisible = false;
                    // 文本框输入的值
                    item.inputValue = ''
                });

                // 判断获取的数据是属于哪个页签的
                if (this.activeName === 'many') {
                    this.manyTableData = res.data;
                } else {
                    this.onlyTableData = res.data;
                };
            },
            // tab 页签点击事件的处理函数
            handleTabClick() {
                // 切换页签时重新获取分类数据
                this.handleChange();
            },
            // 关闭添加参数弹框重置表单
            addDialogVisibleClose() {
                this.$refs.addFormRef.resetFields();
            },
            // 点击确定发送添加参数请求
            addParams() {
                // 预验证
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) return;
                    const { data: res } = await this.$axios.post(`categories/${ this.cateId }/attributes`, {
                        attr_name: this.addForm.attr_name,
                        attr_sel: this.activeName
                    });
                    if (res.meta.status !== 201) return this.$message.error('添加失败');
                    this.$message.success('添加成功');
                    this.handleChange();
                    this.addDialogVisible = false;
                })
            },
            // 删除参数
            async removeParams(id) {
                const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                if (confirmResult !== 'confirm') return this.$message.info('已取消删除');
                const { data: res } = await this.$axios.delete(`categories/${ this.cateId }/attributes/${ id }`);
                if (res.meta.status !== 200) return this.$message.error('删除失败');
                this.$message.success('删除成功');
                this.handleChange();
            },
            // 关闭编辑参数弹框重置表单
            editDialogVisibleClose() {
                this.$refs.editFormRef.resetFields();
            },
            // 点击编辑获取当前参数信息
            async editDialogVisibleShow(id) {
                const { data: res } = await this.$axios.get(`categories/${ this.cateId }/attributes/${ id }`);
                if (res.meta.status !== 200) return this.$message.error('获取失败');
                this.editForm = res.data;
                this.editDialogVisible = true;
            },
            // 点击确定发送修改参数请求
            async editParams() {
                const { data: res } = await this.$axios.put(`categories/${ this.cateId }/attributes/${ this.editForm.attr_id }`, {
                    attr_name: this.editForm.attr_name,
                    attr_sel: this.activeName
                });
                if (res.meta.status !== 200) return this.$message.error('修改失败');
                this.$message.success('修改成功');
                this.handleChange();
                this.editDialogVisible = false;
            },
            // 按下enter 和失去焦点都会触发这个事件
            async handleInputConfirm(row) {
                // 判断文本框输入内容是否为空
                if (row.inputValue.trim().length === 0) {
                    row.inputValue = '';
                    row.inputVisible = false;
                    return
                };
                // 文本框有输入内容，就添加到 attr_vals 数组中
                row.attr_vals.push(row.inputValue.trim());
                // 清空文本框并隐藏
                row.inputValue = '';
                row.inputVisible = false;
                
                this.saveAttrVals(row);
            },
            // 发起请求保存修改的参数
            async saveAttrVals(row) {
                const { data: res } = await this.$axios.put(`categories/${ this.cateId }/attributes/${ row.attr_id }`, {
                    // attr_name: row.inputValue,
                    // attr_sel: this.activeName,
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                });
                if (res.meta.status !== 200) return this.$message.error('修改参数失败');
                this.$message.success('修改参数成功');
                this.handleChange();
            },
            // 控制按钮隐藏，文本框显示
            showInput(row) {
                row.inputVisible = true;
                // 让文本框自动获得焦点 
                //$nextTick: 在页面上元素被重新渲染之后，调用回调函数的代码
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                })
            },
            // 删除参数标签
            handleClose(index, row) {
                // 删除对应索引的参数可选项
                row.attr_vals.splice(index, 1);
                this.saveAttrVals(row);
            }

        },
        computed: {
            // 控制参数按钮是否禁用
            isBtnDisable() {
                if (this.selectKeys.length !== 3) return true;
                return false;
            },
            // 获取级联选择器选中时的分类id
            cateId() {
                if (this.selectKeys.length === 3) {
                    return this.selectKeys[2];
                }
                return null;
            },
            titleText() {
                if (this.activeName === 'many') {
                    return '动态参数';
                } else {
                    return '静态属性';
                }
            }
        }
    }
</script>

<style scoped>
    .shop_list {
        margin: 15px 0;
    }

    .el-tag {
        margin: 0 10px;
    }

    .input-new-tag {
        width: 120px;
    }
</style>